<template>
  <div class="asset-container">
    <div class="asset-title">{{ $t('header.myAssets') }}</div>
    <div class="asset-header">
      <div class="asset-tabs">
        <div v-for="tab in tabs" :key="tab.name" :class="['tab-item', { 'active': tabValue === tab.name }]"
          @click="tabValue = tab.name; selectMet(tab.name)">
          {{ $t(tab.label) }}
        </div>
      </div>
      <div class="bank-record" @click="jumpBank">
        {{ $t('routerTitle.bankRecord') }}
      </div>
    </div>

    <!-- 余额标签页 -->
    <div v-if="tabValue === 'name1'" class="asset-content">
      <div class="balance-card">
        <span class="icon">
          <img src="@/assets/images/icons/icon_balance_2.png" alt="">
        </span>
        <div class="balance-info">
          <h3>{{ $t('user.availableBalance') }}</h3>
          <p class="amount">{{ userInfo.currencySymbol }} {{ userInfo.amount || 0 }}</p>
        </div>
        <div class="balance-actions">

          <router-link :to="{ path: 'withdraw' }" class="action-btn withdraw">
            {{ $t('user.withdraw') }}
          </router-link>
          <button class="action-btn recharge" @click="showPop = true">
            {{ $t('user.recharge') }}
          </button>
        </div>
      </div>

      <div class="transaction-list">
        <div class="transaction-header">
          <div v-for="col in balanceColumns" :key="col" class="col">
            {{ $t(col) }}
          </div>
        </div>
        <div v-if="assetsLoading" class="loading-wrap">
          <t-loading></t-loading>
        </div>
        <div v-else-if="!assetsLoading && dataList.length === 0" class="no-data">
          <t-no-data></t-no-data>
        </div>
        <div v-else class="transaction-body">
          <div v-for="item in dataList" :key="item.payOrderNum" class="transaction-item">
            <div class="col">{{ item.changeTime }}</div>
            <div class="col">{{ item.type }}</div>
            <div class="col">{{ item.changeAmountCurrencySymbol }} {{ item.changeAmount }}</div>
            <div class="col">{{ item.balanceBeforeChangeCurrencySymbol }} {{ item.balanceBeforeChange }}</div>
            <div class="col">{{ item.balanceAfterChangeCurrencySymbol }} {{ item.balanceAfterChange }}</div>
            <div class="col">{{ item.id }}</div>
            <div class="col">{{ item.changeRmk }}</div>
          </div>
        </div>
        <Page v-if="dataList.length > 0" class="pagination" :total="totalPage" @on-page-size-change="onPageSize"
          :current="form.pageNo" @on-change="onPage" :page-size="form.pageSize" show-sizer />
      </div>
    </div>

    <!-- 优惠券标签页 -->
    <div v-if="tabValue === 'name2'" class="asset-content">
      <div class="coupon-filter">
        <div class="coupon-tabs">
          <div v-for="(item, index) in typeArr" :key="index"
            :class="['coupon-tab', { 'active': defaultIndex === index }]"
            @click="defaultIndex !== index ? changeSel(index, item.orderType) : ''">
            {{ item.name }} ({{ compNum(item.orderType) }})
          </div>
        </div>
        <Input class="coupon-search" search :enter-button="$t('personal.Search-confirm')"
          :placeholder="$t('personal.couponCode')" @on-search="onSearch" />
      </div>
      <coupon-list :data="couponList"></coupon-list>
    </div>

    <!-- 金币标签页 -->
    <div v-if="tabValue === 'name3'" class="asset-content">
      <div class="coin-card">
        <div class="coin-info">
          <h3>{{ $t('combination.gold_coin') }}</h3>
          <p class="amount">
            <span class="coin-icon">🪙</span>
            {{ userInfo.goldCoinCNY || 0 }}
            <span class="converted">≈{{ userCurrency.code }} {{ userInfo.goldCoin }}</span>
            <Tooltip :content="$t('combination.coin_tip')" placement="top" max-width="200" transfer>
              <span class="tooltip-icon">?</span>
            </Tooltip>
          </p>
        </div>
      </div>

      <div class="transaction-list">
        <div class="transaction-header">
          <div v-for="col in coinColumns" :key="col" class="col">
            {{ $t(col) }}
          </div>
        </div>
        <div v-if="assetsLoading" class="loading-wrap">
          <t-loading></t-loading>
        </div>
        <div v-else-if="!assetsLoading && dataList.length === 0" class="no-data">
          <t-no-data></t-no-data>
        </div>
        <div v-else class="transaction-body">
          <div v-for="item in dataList" :key="item.payOrderNum" class="transaction-item">
            <div class="col">{{ item.changeTime }}</div>
            <div class="col">{{ item.type }}</div>
            <div class="col">{{ item.changeAmountCurrencySymbol }} {{ item.changeAmount }}</div>
            <div class="col">{{ item.balanceBeforeChangeCurrencySymbol }} {{ item.balanceBeforeChange }}</div>
            <div class="col">{{ item.balanceAfterChangeCurrencySymbol }} {{ item.balanceAfterChange }}</div>
            <div class="col">{{ item.id }}</div>
            <div class="col">{{ item.changeRmk }}</div>
          </div>
        </div>
        <Page v-if="dataList.length > 0" class="pagination" :total="totalPage" @on-page-size-change="onPageSize"
          :current="form.pageNo" @on-change="onPage" :page-size="form.pageSize" show-sizer />
      </div>
    </div>

    <!-- 充值弹窗 -->
    <Modal class="recharge-modal" v-model="showPop" :title="$t('user.rechargeAmountCNY')" @on-cancel="onHidePop">
      <div class="modal-content">
        <label class="input-label">
          {{ $t('user.rechargeAmountCNY') }} <span>*</span>
        </label>
        <Input v-model="dataMoney.amount" :placeholder="$t('user.rechargeAmountCNY')" maxlength="9"
          @on-change="convertInput" type="number">
        <template #append>
          <span>{{ userCurrency.code == 'CNY' ? '' : '≈' }}{{ dataMoney.dollar }}（{{ userCurrency.code }}）</span>
        </template>
        </Input>
      </div>
      <div slot="footer" class="modal-footer">
        <button class="cancel-btn" @click="onHidePop">{{ $t('user.cancel') }}</button>
        <Button type="primary" @click="onRecharge" :loading="loading">
          {{ $t('user.recharge') }}
        </Button>
      </div>
    </Modal>

    <Modal v-model="rechargePop" @on-ok="handleOk" @on-cancel="handlCancel">
      <div class="result-message">{{ resultVal }}</div>
    </Modal>

    <notice ref="notice" />
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { changeRecord, recharge, convert, myCouponStat } from "@/api/user";
import { mapState } from "vuex";
import { myCouponList, exchangeCoupon } from "@/api/order";
import TLoading from "@/components/t-loading";
import { debounce } from "@/common/common";
import notice from "@/components/t-noticeModal";
import { query } from "vue-gtag";
import CouponList from './components/coupon-list.vue';

export default {
  name: "points",
  components: { TLoading, notice, CouponList },
  data() {
    return {
      resultVal: '',
      rechargePop: false,
      dataMoney: {
        amount: '', // 充值金额
        dollar: '',
        highestAmount: 10
      },
      assetsLoading: false,
      loading: false,
      showPop: false,
      modal1: false,
      tabValue: 'name1',
      amount: '',
      dataList: [], // 资产明细记录
      totalPage: 1,
      form: {
        changeType: 'BALANCE',//调账类型 BALANCE 余额 GOLD_COIN 金币
        orderNum: '', // 订单号
        pageNo: 1, // 页
        pageSize: 20, // 页数
      },
      couponList: [],
      countObj: {},
      defaultIndex: 0,
      typeArr: [
        { name: this.$t('user.order_coupon_tit'), orderType: 'ORDER' },
        { name: this.$t('user.express_coupon_tit'), orderType: 'EXPRESS' },
        { name: this.$t('user.expired_tab_text'), orderType: 'EXPIRED' }
      ],
      tabs: [
        { label: 'user.balance', name: 'name1' },
        { label: 'user.coupon', name: 'name2' },
        { label: 'combination.gold_coin', name: 'name3' }
      ],
      balanceColumns: [
        'user.tradingTime',
        'user.type',
        'user.incomeExpenditure',
        'user.balanceBeforeConversion',
        'user.balanceAfterConversion',
        'user.transactionNumber',
        'user.remark'
      ],
      coinColumns: [
        'user.tradingTime',
        'user.type',
        'user.incomeExpenditure',
        'combination.account_change_before_coin',
        'combination.account_change_after_coin',
        'user.transactionNumber',
        'user.remark'
      ]
    }
  },
  computed: {
    ...mapState({
      userCurrency: state => state.user.userCurrency,
      userInfo: state => state.user.userInfo,
      userLanguage: state => state.user.userLanguage,
    })
  },
  created() {
    const { from } = this.$route.query
    this.tabValue = from || 'name1'
    this.getDataList();
    this.getCouponNum();
    this.getMyCouponList('ORDER');
  },
  methods: {
    onSearch(v) {
      exchangeCoupon({ idSet: [v] }).then(({ message }) => {
        this.$Message.success(message || 'Success!');
        this.getMyCouponList();
      }).catch()
    },
    getCouponNum() {
      myCouponStat().then((res) => {
        this.countObj = res.result;
      })
    },
    getMyCouponList(e) {
      myCouponList().then((res) => {
        if (e == 'EXPRESS') {
          const now = Date.now();
          this.couponList = (res.result.filter(item => {
            return (item.status == 'UNUSED' || item.status == 'LOCKED') && item.expiredAt > now && item.targetObject == 'EXPRESS';
          }) || []).sort((a, b) => {
            const dayA = dayjs(a.endTime);
            const dayB = dayjs(b.endTime);
            if (dayA.isBefore(dayB)) {
              return -1;
            } else if (dayA.isAfter(dayB)) {
              return 1;
            }
            return 0;
          });
        } else if (e == 'ORDER') {
          const now = Date.now();
          this.couponList = (res.result.filter(item => {
            return (item.status == 'UNUSED' || item.status == 'LOCKED') && item.expiredAt > now && item.targetObject == 'ORDER';
          }) || []).sort((a, b) => {
            const dayA = dayjs(a.endTime);
            const dayB = dayjs(b.endTime);
            if (dayA.isBefore(dayB)) {
              return -1;
            } else if (dayA.isAfter(dayB)) {
              return 1;
            }
            return 0;
          });
        } else if (e == 'EXPIRED') {
          const now = Date.now();
          this.couponList = (res.result.filter(item => {
            return item.status == 'EXPIRED' && item.expiredAt <= now;
          }) || []).sort((a, b) => {
            const dayA = dayjs(a.endTime);
            const dayB = dayjs(b.endTime);
            if (dayA.isBefore(dayB)) {
              return 1;
            } else if (dayA.isAfter(dayB)) {
              return -1;
            }
            return 0;
          });
        } else {
          const now = Date.now();
          this.couponList = (res.result.filter(item => {
            return (item.status == 'UNUSED' || item.status == 'LOCKED') && item.expiredAt >= now && item.status != 'EXPIRED';
          }) || []).sort((a, b) => {
            if (a.targetObject === 'ORDER' && b.targetObject === 'EXPRESS') {
              return -1;
            } else if (a.targetObject === 'EXPRESS' && b.targetObject === 'ORDER') {
              return 1;
            }
            const dayA = dayjs(a.endTime);
            const dayB = dayjs(b.endTime);
            if (dayA.isBefore(dayB)) {
              return -1;
            } else if (dayA.isAfter(dayB)) {
              return 1;
            }
            return 0;
          });
        }
      }).catch()
    },
    compNum(orderType) {
      if (orderType == 'EXPRESS') {
        return this.countObj.expressCount;
      } else if (orderType == 'ORDER') {
        return this.countObj.orderCount;
      } else if (orderType == 'EXPIRED') {
        return this.countObj.expired;
      } else {
        return this.countObj.allCount;
      }
    },
    changeSel(e, v) {
      this.defaultIndex = e;
      this.getMyCouponList(v);
    },
    onHidePop() {
      this.dataMoney = {
        amount: '',
        dollar: '',
        highestAmount: 10
      }
      this.showPop = false;
    },
    onPage(index) {
      this.form.pageNo = index;
      this.getDataList();
    },
    onPageSize(size) {
      this.form.pageSize = size;
      this.form.pageNo = 1;
      this.getDataList();
    },
    getDataList() {
      this.assetsLoading = true;
      this.getInfo();
    },
    getInfo() {
      changeRecord(this.form).then((res) => {
        this.dataList = res.result.records;
        this.totalPage = res.result.total;
        this.assetsLoading = false;
      }).catch(() => {
        this.assetsLoading = false;
      })
    },
    convertInput: debounce(function () {
      this.checkLength()
      if (this.dataMoney.amount) {
        convert({ amount: this.dataMoney.amount, currencyCode: this.userCurrency.code }).then((res) => {
          this.dataMoney.dollar = res.result.calculateOrderAmount
        })
      } else {
        this.dataMoney.dollar = ''
      }
    }, 1000),
    checkLength() {
      const maxLength = 9;
      if (this.dataMoney.amount.length > maxLength) {
        this.dataMoney.amount = this.dataMoney.amount.slice(0, maxLength);
        this.$Message.error(this.$t('pay.greaterThan'));
        return
      }
    },
    onRecharge() {
      if (!this.dataMoney.amount) {
        this.$Message.error(this.$t('pay.RechargeAmount'));
        return
      }
      if (this.dataMoney.amount < this.dataMoney.highestAmount) {
        this.$Message.error(this.$t('pay.minimum', { highestAmount: this.dataMoney.highestAmount }));
        return
      }
      this.loading = true;
      recharge(this.dataMoney.amount).then((res) => {
        if (res.code == 1002) {
          this.rechargePop = true;
          this.resultVal = res.message;
        } else {
          this.onHidePop()
          this.loading = false;
          this.showPop = false;
          let type = "recharge";
          this.$router.push(`/pay?id=${res.result}&&type=${type}&&markText=recharge`);
        }
      }).catch(() => {
        this.loading = false;
      })
    },
    handleOk() {
      this.$router.push('/user/setting')
    },
    handlCancel() {
      this.loading = false;
      this.$refs.rechargePop = false;
    },
    selectMet(name) {
      if (name === 'name3') {
        this.form.changeType = 'GOLD_COIN';
        this.getInfo();
      } else if (name === 'name1') {
        this.form.changeType = 'BALANCE';
        this.getInfo();
      }
    },
    jumpBank() {
      this.$router.push('/user/remittanceRecord')
    },
    enterShow() {
      this.showPop = false;
      this.$router.push('/bankRemittance');
    }
  }
}
</script>

<style scoped lang="less">
.asset-container {
  max-width: 1200px;
  border-radius: 20px;
  background: #FFF;
  padding: 20px;

  .asset-title {
    color: #2F333A;
    font-family: Inter;
    font-size: 20px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
    margin-bottom: 12px;
  }

  .asset-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    border-bottom: 1px solid #eaeaea;
    padding-bottom: 16px;

    .asset-tabs {
      display: flex;
      gap: 24px;

      .tab-item {
        padding: 8px 16px;
        cursor: pointer;
        color: #666;
        font-weight: 500;
        border-bottom: 2px solid transparent;
        transition: all 0.3s;

        &.active {
          color: #FF186B;
          border-bottom-color: #FF186B;
        }

        &:hover {
          color: #FF186B;
        }
      }
    }

    .bank-record {
      color: #FF186B;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .asset-content {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 24px;
  }

  .balance-card,
  .coin-card {
    border-radius: 12px;
    background: #FF186B;
    padding: 16px;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .icon {
      display: block;
      width: 50px;
      height: 50px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h3 {
      margin: 0 0 5px 0;
      font-size: 12px;
      color: #fff;
      font-weight: normal;
    }

    .balance-info {
      flex: 1;
      padding-left: 10px;
    }

    .amount {
      font-size: 16px;
      font-weight: bold;
      color: #fff;
      margin: 0;

      .coin-icon {
        font-size: 24px;
        margin-right: 8px;
      }

      .converted {
        font-size: 16px;
        color: #fff;
        margin-left: 8px;
      }

      .tooltip-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 18px;
        height: 18px;
        background: #666;
        color: white;
        border-radius: 50%;
        font-size: 12px;
        margin-left: 8px;
        cursor: pointer;
      }
    }
  }

  .balance-actions {
    display: flex;
    gap: 16px;

    .action-btn {
      padding: 0 24px;
      height: 32px;
      border-radius: 4px;
      font-weight: 500;
      cursor: pointer;
      border: none;
      transition: all 0.3s;
      line-height: 32px;

      &.recharge {
        background: #FFF;
        color: #FF186B;

      }

      &.withdraw {
        border: 1px solid #fff;
        color: #fff;

      }
    }
  }

  .transaction-list {
    .transaction-header {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      background: #f5f5f5;
      padding: 12px 16px;
      border-radius: 4px;
      margin-bottom: 8px;
      font-weight: 500;
      color: #969696;
      font-size: 12px;

      .col {
        padding: 0 8px;
      }
    }

    .transaction-body {
      .transaction-item {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        transition: background 0.3s;
        font-size: 12px;

        &:hover {
          background: #fafafa;
        }

        .col {
          padding: 0 8px;
          word-break: break-word;
        }
      }
    }

    .loading-wrap,
    .no-data {
      padding: 40px 0;
      text-align: center;
    }

    .pagination {
      margin-top: 24px;
      text-align: right;
    }
  }

  .coupon-filter {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;

    .coupon-tabs {
      display: flex;
      gap: 8px;

      .coupon-tab {
        padding: 8px 16px;
        border-radius: 6px;
        border: 1px solid #F1F1F1;
        cursor: pointer;
        transition: all 0.3s;
        font-size: 13px;

        &.active {
          background: #FF186B;
          color: white;
        }

        &:hover:not(.active) {
          background: #FF186B;
          color: white;
        }
      }
    }

    .coupon-search {
      width: 300px;
    }
  }
}

.recharge-modal {
  .modal-content {
    .input-label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;

      span {
        color: #ff4d4f;
      }
    }
  }

  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 16px;

    .cancel-btn {
      padding: 8px 16px;
      background: white;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        color: #1890ff;
        border-color: #1890ff;
      }
    }

    .confirm-btn {
      padding: 8px 16px;
      background: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #40a9ff;
      }

      &[loading] {
        opacity: 0.6;
      }
    }
  }
}

.result-message {
  padding: 20px;
  font-size: 16px;
  text-align: center;
}
</style>